#include "hex_parser.h"
#include <iostream>
#include <string>

void printUsage(const char* program_name) {
    std::cout << "Usage: " << program_name << " <hex_file_path_or_single_record>" << std::endl;
    std::cout << "Examples:" << std::endl;
    std::cout << "  " << program_name << " M6_HMI_LOADER.hex" << std::endl;
    std::cout << "  " << program_name << " :04000005080003A547" << std::endl;
}

int main(int argc, char* argv[]) {
    if (argc != 2) {
        std::cerr << "Error: Incorrect number of arguments" << std::endl;
        printUsage(argv[0]);
        return 1;
    }
    
    std::string input = argv[1];
    
    // 检查是否是单行HEX记录
    bool is_single_line = (input.length() > 0 && input[0] == ':');
    
    if (!is_single_line) {
        // 检查文件扩展名
        if (input.length() < 4 || 
            input.substr(input.length() - 4) != ".hex") {
            std::cerr << "Error: Input must be either a .hex file or a single HEX record starting with ':'" << std::endl;
            return 1;
        }
    }
    
    std::cout << "Parsing HEX " << (is_single_line ? "record" : "file") << ": " << input << std::endl;
    
    HexParser parser;
    
    bool parse_success;
    if (is_single_line) {
        parse_success = parser.parseSingleRecord(input);
    } else {
        parse_success = parser.parseFile(input);
    }
    
    if (!parse_success) {
        std::cerr << "Failed to parse " << (is_single_line ? "record" : "file") << std::endl;
        return 1;
    }
    
    // 验证文件格式
    if (!parser.validateFile()) {
        std::cerr << "File format validation failed" << std::endl;
        return 1;
    }
    
    // 打印文件信息
    parser.printFileInfo();
    
    // 只有完整HEX文件才显示段信息
    if (!is_single_line) {
        // 分析并打印段信息
        parser.analyzeSegments();
        parser.printSegmentInfo();
    }
    
    // 显示一些示例数据
    const auto& file_info = parser.getFileInfo();
    if (!file_info.memory_map.empty()) {
        std::cout << "\n=== Sample Data Reading ===" << std::endl;
        
        // Read first 16 bytes of data
        auto data = parser.getDataAtAddress(file_info.start_address, 16);
        std::cout << "First 16 bytes from start address 0x" << std::hex << std::uppercase << file_info.start_address 
                  << ":" << std::endl;
        
        for (size_t i = 0; i < data.size(); ++i) {
            if (i % 8 == 0) {
                std::cout << "\n  0x" << std::hex << std::uppercase << std::setfill('0') 
                          << std::setw(8) << (file_info.start_address + i) << ": ";
            }
            std::cout << std::hex << std::uppercase << std::setfill('0') << std::setw(2) 
                      << static_cast<int>(data[i]) << " ";
        }
        std::cout << std::endl;
    }
    
    std::cout << "\nHEX file parsing completed!" << std::endl;
    return 0;
}
